package utils

import (
	"log"
	"os"
	"path/filepath"
	"strings"
)

// JoinPath 拼接路径
func JoinPath(path ...string) string {
	var res string

	for i, item := range path {
		if i == 0 {
			res += item
		} else {
			res += "\\" + item
		}

	}

	return res
}

func ListContains(path string, list []string, debug bool) bool {
	for _, item := range list {
		if path == item {
			if debug {
				log.Printf("ignore file at \"%v\"\n", path)
			}
			return true
		}
	}

	return false
}

func MatchIgnore(path string, list []string, debug bool) bool {
	if len(list) == 0 {
		return false
	}

	for _, item := range list {
		if strings.Contains(item, "*") {

			fileList, err := filepath.Glob(item)
			if err != nil {
				log.Fatalln(err)
			}

			flag := ListContains(path, fileList, debug)
			if flag {
				return flag
			}
		} else {
			flag := strings.HasPrefix(path, item)
			if flag {
				return flag
			}
		}
	}

	return false
}

func RemoveAllEmptyDir(root string, ignoreList []string, doLog bool) error {

	dirNames := make([]string, 0)
	fileNames := make([]string, 0)

	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {

		if MatchIgnore(path, ignoreList, true) {
			return err
		}
		if info.IsDir() {
			dirNames = append(dirNames, path)
		} else {
			fileNames = append(fileNames, path)
		}
		return err
	})

	if err != nil {
		return err
	}

	fileNamesAll := strings.Join(fileNames, "")

	for i := len(dirNames) - 1; i >= 0; i-- {

		if !strings.Contains(fileNamesAll, dirNames[i]) && !MatchIgnore(dirNames[i], ignoreList, false) {
			if doLog {
				log.Printf("find and remove empty folder at \"%v\"\n", dirNames[i])
			}

			err := os.RemoveAll(dirNames[i])
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func GetExt(path string) string {
	return strings.ToLower(filepath.Ext(path))
}

func UnifyExtname(ext string) string {

	if len(ext) == 0 {
		return ext
	}

	ext = strings.ToLower(ext)
	if !strings.HasPrefix(ext, ".") {
		return "." + ext
	} else {
		return ext
	}

}
